import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import cart from "../../../../store/cart";

Component({
  options: {
    addGlobalClass: true,
  },
  behaviors: [storeBindingsBehavior],
  storeBindings: [
    {
      store: cart,
      actions: ["addCart"],
    },
  ],
  data: {
    visible: false,
    goods: null,
    spec: "",
    specPrice: 0,
    resolve: null,
    reject: null,
    selectAttrList: [],
    tips: "",
  },
  observers: {
    "spec,selectAttrList": function (spec, selectAttrList) {
      let tips = [];
      if (spec) {
        tips.push(spec);
      }
      tips.push(...selectAttrList);
      this.setData({ tips: tips.join(",") });
    },
  },
  methods: {
    handleClose() {
      this.setData({ visible: false });
    },
    handleStop() {
      return true;
    },
    open(goods) {
      this.reset(goods);
      this.setData({ visible: true });
    },
    reset(goods) {
      let spec = "",
        specPrice,
        selectAttrList = [];
      if (goods.specList && goods.specList.length > 0) {
        spec = goods.specList[0].name;
        specPrice = goods.specList[0].price;
      }
      if (goods.attrList && goods.attrList.length > 0) {
        for (let item of goods.attrList) {
          selectAttrList.push(item.values[0]);
        }
      }
      this.setData({ goods, spec, specPrice, selectAttrList });
    },
    handleSelectSpec(e) {
      let item = e.currentTarget.dataset.item;
      if (item.name === this.data.spec) {
        return;
      }
      this.setData({
        spec: item.name,
        specPrice: item.price,
      });
    },
    handleSelectAttr(e) {
      let { index, value } = e.currentTarget.dataset;
      let selectAttrList = this.data.selectAttrList;
      selectAttrList[index] = value;
      this.setData({ selectAttrList });
    },
    handleConfirm() {
      let specPrice = this.data.specPrice,
        spec = this.data.spec,
        attrList = this.data.selectAttrList;
      const item = {};
      item.name = this.data.goods.name;
      item.id = this.data.goods.id;
      item.count = 1;
      item.spec = spec;
      if (spec) {
        item.price = specPrice;
      } else {
        item.price = this.data.goods.price;
      }
      item.attrList = attrList;
      this.addCart(item);
      this.setData({ visible: false });
    },
  },




});
